let cacheD2Data = [];
let cacheD1Item = null;
let cacheD2RowLength = 0;
let _fenliuLock = 0;
let _datas = {};
let currentRow = -1;
let shangRow = -1;
$NG.AllReady(function (editPage, { useUpdateRows, useValuesChange, useUpdateRow, useDataIndexChange, useClick }) {
  var mstform = $NG.getCmpApi("p_form_gzdyqd"); //获取表头数据
  var dgrid1 = $NG.getCmpApi("p_form_gzdyqd_d"); //工作单元
  var dgrid2 = $NG.getCmpApi("p_form_gzdyqd_d1"); //设备清单
  ////////////////////////////////////////////////////////////--按钮事件--////////////////////////////////////////////////////////////
  //   $NG.getCmpApi("toolbar_p_form_gzdyqd_d").getItem("imp").setHidden();
  //   $NG.getCmpApi("toolbar_p_form_gzdyqd_d").hideButton("imp");
  // $NG.getCmpApi("toolbar_p_form_gzdyqd_d1").hideButton("addrow");
  //   $NG.getCmpApi("toolbar_p_form_gzdyqd_d1").getItem("addrow").setHidden();
  $NG.getCmpApi("toolbar_p_form_gzdyqd_d1").insert({
    id: "myadd",
    text: "引用设备清单",
    iconCls: "icon-New",
  });
  $NG.getCmpApi("toolbar_p_form_gzdyqd_d").insert({
    id: "copyrow",
    text: "复制",
    iconCls: "icon-New",
  });
  useClick(async function ({ args }) {
    myaddClick();
  }, "myadd");

  //复制逻辑
  useClick(()=>{
    console.log(`您点击了复制`);
    onCopyClick()
  },"copyrow")
  ////////////////////////////////////////////////////////////--myaddClick--////////////////////////////////////////////////////////////
  function myaddClick() {
    if (!dgrid1.getSelectedData()[0]) {
      $NG.alert("请先选择对应的工作单元");
      return;
    }
    if (!mstform.getItem("phid_pc").getValue()) {
      $NG.alert("请先选择项目");
      return;
    }
    // console.log("phid_pc:" + mstform.getItem("phid_pc").getValue());
    $NG.external
      .openNGHelp({
        type: "NGMultipleHelp",
        helpId: "sbqd",
        valueField: "phid",
        labelField: "d.u_equipment_list_name",
        clientSqlFilter: `m.phid_pc = ${mstform.getItem("phid_pc").getValue()}`,
      })
      .then((data) => {
        if (Array.isArray(data) && data.length > 0) {
          console.log(data);
          var gridArr = [];
          var gridCount = data.length;
          console.log(gridCount);
          for (var i = 0; i < gridCount; i++) {
            var gridObj = {};
            gridObj.rel_key1 = dgrid1.getSelectedData()[0].rel_key1;
            gridObj.u_revenue_type = data[i].origin.u_revenue_type;
            gridObj.u_revenue_type_EXName = data[i].origin.c_name;
            gridObj.u_sbqd_no = data[i].origin.u_equipment_list_no;
            gridObj.u_sbqd_name = data[i].origin.phid;
            gridObj.u_sbqd_name_EXName = data[i].origin.u_equipment_list_name || "";
            gridObj.u_cnt_d_no = data[i].origin.u_cnt_item_no;
            gridObj.u_cnt_d_name = data[i].origin.item_name;
            gridObj.u_xh = data[i].origin.u_spec;
            gridObj.u_jscs = data[i].origin.u_tech_params;
            gridObj.u_gcfxfl = data[i].origin.u_pc_subitem_category;
            gridObj.u_msunit = data[i].origin.u_msunit;
            gridObj.u_msunit_EXName = data[i].origin.Msname;
            gridObj.u_brand = data[i].origin.u_brand;
            gridObj.u_brand_EXName = data[i].origin.compname;
            gridObj.u_cnt_qty = data[i].origin.u_qty;
            gridObj.u_cnt_prc = data[i].origin.u_cnt_prc;
            gridObj.u_cnt_amt = data[i].origin.u_cnt_amt;
            gridArr.push(gridObj);
          }
          console.log(gridArr);
          dgrid2.addRows(gridArr);
          dgrid2.refreshView();
        }
      });
  }
//复制逻辑
  function onCopyClick(){
    const checkRow = dgrid1.getSelectedData()
    console.log(`copy行`,checkRow);
    switch(checkRow.length){
        case 0:
            $NG.alert("请选中一行进行复制！")
            break;
        case 1:
            console.log(`正在进项复制`)
            const _AllDataD2 = dgrid2.getRows()
            const _tempCheakArr = []
            //找到表体2中相应的数据
            _AllDataD2.forEach((item)=>{
                if(item.rel_key1 === checkRow[0].rel_key1){
                    _tempCheakArr.push(item)
                }
            })
            console.log(`找到表体1对应的2数据了`,_tempCheakArr);
            //模拟点击按钮进行新增
            $NG.getCmpApi("toolbar_p_form_gzdyqd_d").getItem("addrow").getRef().click();
           setTimeout(()=>{
             //取出最后一个新增数据
             const _tempData = dgrid1.getRows()
             const _tempItem = _tempData[_tempData.length-1]
             console.log(`新增数据`,_tempItem,_tempData);
             _tempItem["u_lx"] = checkRow[0].u_lx 
             _tempItem["u_sfjbjm"] = checkRow[0].u_sfjbjm 
             _tempItem["u_sggxqd"] = checkRow[0].u_sggxqd 
             _tempItem["u_sggxqd_EXName"] = checkRow[0].u_sggxqd_EXName
             _tempItem["u_amt"] = checkRow[0].u_amt
             let addData = _tempCheakArr.reduce((value,item)=>{
                value.push({...item})
                return value
             },[])
             addData.forEach((item)=>{
                 item.rel_key1 = _tempItem.rel_key1
             })
             dgrid2.addRows(addData)
             dgrid1.refreshView()
             dgrid2.refreshView()
           },300)
            break;
        default:
            $NG.alert("请不要选中多行，支持一行复制新增！")
    }
  }
  //对象浅复制
  function shallowTraverse(obj) {
    const _temp = {}
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        _temp[key]=obj[key];
      }
    }
    return _temp
  }
  

  
  // 方法内缓存
  let LockMap = {
    _d2AddBtn: false,
    set d2AddBtn(value) {
      //表体按钮置灰
      $NG.getCmpApi("toolbar_p_form_gzdyqd_d1").getItem("addrow").setDisabled(value);
      this._d2AddBtn = value;
    },
    get d2AddBtn() {
      return this._d2AddBtn;
    },
  };

  {
    //初始化逻辑BEGIN
    if (mstform.getItem("phid_pc").getValue()) {
      cntMFilter();
      getPtInfoByPhid();
    }
  } //初始化逻辑END
  {
    //表头字段变化逻辑BEGIN
    useValuesChange(({ args }) => {
      cntMFilter();
      getPtInfoByPhid();
    }, "p_form_gzdyqd.phid_pc");
    useValuesChange(({ args }) => {
      getCntMInfoByPhid();
      getQdDetail()
    }, "p_form_gzdyqd.u_cnt");
  } //表头字段变化逻辑END

  useUpdateRow(({args})=>{
    const _map = args[0]
    const _arr = dgrid2.getRows()
    //点位数量累计
    let _count = 0
    _arr.forEach(item=>{
        if(item.u_sbqd_no == _map.u_sbqd_no){
            _count+=(Number(item.u_point_qty) || 0)
        }
    })
    //判断是否超出
    window._lsz_catch_qdDetail.forEach(item=>{
        if(item.u_equipment_list_no == _map.u_sbqd_no){
            if(item.u_qty<_count){
                _map.u_point_qty = null
                $NG.alert("点位数量超出设备清单合同数量！")
            }
        }
    })
  },"p_form_gzdyqd_d1")

  useUpdateRow(({ args, table }) => {
    const record = args[0];
    if (!isNaN(parseFloat(record.u_point_qty)) && !isNaN(parseFloat(record.u_cnt_prc))) {
      record.amt = (parseFloat(record.u_cnt_prc) * parseFloat(record.u_point_qty)).toFixed(2);
    }

    dgrid2.updateRow(record);
    dgridSum();
  }, "p_form_gzdyqd_d1");

  ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
  function dgridSum() {
    var selectedData = dgrid1.getSelectedData()[0] || {};
    console.log("selectedData:" + dgrid1.getSelectedData()[0].u_gzdy_code);
    var rel_key1 = selectedData.rel_key1 || "";
    if (!rel_key1) return; // 若未选择行或 rel_key1 为空，直接返回
    let u_total_amt = 0;
    dgrid2.getRows().forEach(function (item) {
      if (item.rel_key1 === rel_key1) {
        u_total_amt += parseFloat(item.amt) || 0;
      }
    });
    console.log("u_total_amt:" + u_total_amt);
    dgrid1.getRows().forEach(function (item) {
      if (item.rel_key1 === rel_key1) {
        item.u_amt = u_total_amt;
        // console.log("item.u_amt:" + item.u_amt);
      }
    });
    dgrid1.refreshView();
  }

  function getPtInfoByPhid() {
    if (mstform.getItem("phid_pc").getValue()) {
      $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(datas);
        //帮助字段赋值
        $NG.updateState((updater) => {
          updater.data.p_form_gzdyqd.setProps({
            u_pc_no: datas.pc_no, //项目编码
            u_sqgw: {
              //售前顾问
              value: datas.user_sqgw_phid,
              label: datas.user_sqgw_name,
            },
            u_xmjl: {
              //项目经理
              value: datas.project_manager_phid,
              label: datas.project_manager_name,
            },
            u_khjl: {
              //客户经理
              value: datas.project_manager_phid,
              label: datas.project_manager_name,
            },
          });
        });
      });
    }
  }
  cntMFilter();
  function cntMFilter() {
    $NG.updateUI((updater, state) => {
      updater.fieldSetForm.p_form_gzdyqd.u_cnt.setProps({
        onBeforeOpen: async () => {
          var phid_pc = mstform.getItem("phid_pc").getValue();
          if (!phid_pc) {
            $NG.alert("请先选择项目");
            return false;
          } else {
            return true;
          }
        },
        ...(!!mstform.getItem("phid_pc").getValue() && {
          clientSqlFilter: {
            bill_type: 1, //合同类型1:承包合同|4:分包合同;
            phid_pc: mstform.getItem("phid_pc").getValue(),
          },
        }),
      });
    });
  }

  function getCntMInfoByPhid(params) {
    $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      console.log(datas);
      $NG.updateState((updater) => {
        updater.data.p_form_gzdyqd.setProps({
          u_cnt_no: datas.pcm_no, //合同编码
          u_kh_name: {
            //甲方单位
            value: datas.customer_id,
            label: datas.customer_name,
          },
        });
      });
    });
  }

  setTimeout(() => {
    console.log(`开始触发`);
    const button = document.getElementById("toolbar_top");

    // 创建鼠标点击事件对象
    const clickEvent = new MouseEvent("click", {
      bubbles: true,
      cancelable: true,
      // 假设这里添加自定义的origin属性，根据实际需求设置其值
      originid: "save",
    });
    Object.defineProperty(clickEvent, "originid", {
      value: "save",
      enumerable: true,
    });
    button.dispatchEvent(clickEvent);
  }, 5000);

  //获取清单明细
  function getQdDetail(){
    $NG.execServer("getEqdInfoByPhid_cnt",{phid_cnt:mstform.getItem("u_cnt").getValue()},(res)=>{
        console.log(`获取清单明细`,res);
        if(res.count == 0) return 
        const _data = JSON.parse(res.data)
        console.log(_data);
        const _Temp = []
        _data.forEach(item=>{
            _Temp.push(item.extendObjects)
        })
        window._lsz_catch_qdDetail = [..._Temp]
    })
  }
});
